/**
 * Agent执行器 - IntelliMark适配版
 * 负责管理和执行多个AI代理
 */

import { AgentConfig, AgentResult, WritingContext } from "../types/agent";
import { WritingAgent, WritingTask } from "./writingAgent";
import { getToolManager } from "../tools";
import { v4 as uuidv4 } from 'uuid';

// 执行器配置
export interface AgentExecutorConfig {
  maxConcurrentAgents: number;
  defaultTimeout: number;
  enableTaskQueue: boolean;
  maxQueueSize: number;
  retryAttempts: number;
  enableLogging: boolean;
}

// 执行任务
export interface ExecutionTask {
  id: string;
  agentName: string;
  task: any;
  priority: number;
  createdAt: Date;
  timeout?: number;
  retries: number;
  maxRetries: number;
}

// 执行结果
export interface ExecutionResult {
  taskId: string;
  agentName: string;
  result: AgentResult;
  executionTime: number;
  startTime: Date;
  endTime: Date;
}

export class AgentExecutor {
  private config: AgentExecutorConfig;
  private agents: Map<string, any> = new Map();
  private taskQueue: ExecutionTask[] = [];
  private runningTasks: Map<string, ExecutionTask> = new Map();
  private isProcessing = false;
  private executionHistory: ExecutionResult[] = [];

  constructor(config: Partial<AgentExecutorConfig> = {}) {
    this.config = {
      maxConcurrentAgents: 3,
      defaultTimeout: 60000, // 60秒
      enableTaskQueue: true,
      maxQueueSize: 100,
      retryAttempts: 3,
      enableLogging: true,
      ...config,
    };

    this.initializeDefaultAgents();
  }

  // 初始化默认代理
  private initializeDefaultAgents(): void {
    // 注册写作代理
    const writingAgent = new WritingAgent({
      specialties: ['generate', 'polish', 'expand', 'continue', 'summarize'],
      defaultStyle: 'creative',
      autoContext: true,
      learningEnabled: true,
      collaborationMode: false,
      memoryEnabled: true,
    });

    this.registerAgent('writing', writingAgent);

    if (this.config.enableLogging) {
      console.log('AgentExecutor initialized with default agents');
    }
  }

  // 注册代理
  public registerAgent(name: string, agent: any): void {
    this.agents.set(name, agent);
    if (this.config.enableLogging) {
      console.log(`Agent registered: ${name}`);
    }
  }

  // 获取代理
  public getAgent(name: string): any {
    return this.agents.get(name);
  }

  // 列出所有代理
  public listAgents(): string[] {
    return Array.from(this.agents.keys());
  }

  // 执行任务
  public async executeTask(
    agentName: string,
    task: any,
    options: { priority?: number; timeout?: number } = {}
  ): Promise<ExecutionResult> {
    const taskId = uuidv4();
    const startTime = new Date();

    const executionTask: ExecutionTask = {
      id: taskId,
      agentName,
      task,
      priority: options.priority || 1,
      createdAt: startTime,
      timeout: options.timeout || this.config.defaultTimeout,
      retries: 0,
      maxRetries: this.config.retryAttempts,
    };

    // 直接执行（如果未启用队列）
    if (!this.config.enableTaskQueue) {
      return this.executeTaskDirect(executionTask);
    }

    // 添加到队列
    return this.addToQueue(executionTask);
  }

  // 直接执行任务
  private async executeTaskDirect(executionTask: ExecutionTask): Promise<ExecutionResult> {
    const startTime = Date.now();
    const agent = this.getAgent(executionTask.agentName);

    if (!agent) {
      throw new Error(`Agent not found: ${executionTask.agentName}`);
    }

    this.runningTasks.set(executionTask.id, executionTask);

    try {
      let result: AgentResult;

      // 设置超时
      const timeoutPromise = new Promise<never>((_, reject) => {
        setTimeout(() => {
          reject(new Error(`Task timeout: ${executionTask.id}`));
        }, executionTask.timeout);
      });

      // 执行任务
      const taskPromise = this.performTask(agent, executionTask.task);

      result = await Promise.race([taskPromise, timeoutPromise]);

      const endTime = new Date();
      const executionTime = Date.now() - startTime;

      const executionResult: ExecutionResult = {
        taskId: executionTask.id,
        agentName: executionTask.agentName,
        result,
        executionTime,
        startTime: new Date(executionTask.createdAt),
        endTime,
      };

      // 记录执行历史
      this.executionHistory.push(executionResult);

      // 清理运行任务
      this.runningTasks.delete(executionTask.id);

      if (this.config.enableLogging) {
        console.log(`Task completed: ${executionTask.id} by ${executionTask.agentName} in ${executionTime}ms`);
      }

      return executionResult;

    } catch (error) {
      const endTime = new Date();
      const executionTime = Date.now() - startTime;

      const executionResult: ExecutionResult = {
        taskId: executionTask.id,
        agentName: executionTask.agentName,
        result: {
          success: false,
          error: error instanceof Error ? error.message : String(error),
        },
        executionTime,
        startTime: new Date(executionTask.createdAt),
        endTime,
      };

      // 重试逻辑
      if (executionTask.retries < executionTask.maxRetries) {
        executionTask.retries++;
        if (this.config.enableLogging) {
          console.log(`Retrying task: ${executionTask.id} (attempt ${executionTask.retries}/${executionTask.maxRetries})`);
        }
        return this.executeTaskDirect(executionTask);
      }

      this.runningTasks.delete(executionTask.id);
      this.executionHistory.push(executionResult);

      if (this.config.enableLogging) {
        console.error(`Task failed: ${executionTask.id}`, error);
      }

      return executionResult;
    }
  }

  // 添加到队列
  private async addToQueue(executionTask: ExecutionTask): Promise<ExecutionResult> {
    if (this.taskQueue.length >= this.config.maxQueueSize) {
      throw new Error('Task queue is full');
    }

    this.taskQueue.push(executionTask);

    // 按优先级排序
    this.taskQueue.sort((a, b) => b.priority - a.priority);

    // 启动队列处理
    if (!this.isProcessing) {
      this.processQueue();
    }

    // 等待任务完成
    return new Promise((resolve, reject) => {
      const checkCompletion = () => {
        const result = this.executionHistory.find(r => r.taskId === executionTask.id);
        if (result) {
          if (result.result.success) {
            resolve(result);
          } else {
            reject(new Error(result.result.error || 'Task failed'));
          }
        } else {
          setTimeout(checkCompletion, 100);
        }
      };
      checkCompletion();
    });
  }

  // 处理队列
  private async processQueue(): Promise<void> {
    if (this.isProcessing || this.taskQueue.length === 0) {
      return;
    }

    this.isProcessing = true;

    while (this.taskQueue.length > 0 && this.runningTasks.size < this.config.maxConcurrentAgents) {
      const task = this.taskQueue.shift();
      if (!task) break;

      // 异步执行任务
      this.executeTaskDirect(task).catch(error => {
        console.error(`Queue task failed: ${task.id}`, error);
      });
    }

    this.isProcessing = false;

    // 如果还有任务在队列中，继续处理
    if (this.taskQueue.length > 0) {
      setTimeout(() => this.processQueue(), 100);
    }
  }

  // 执行具体任务
  private async performTask(agent: any, task: any): Promise<AgentResult> {
    if (agent.processTask) {
      // WritingAgent
      return await agent.processTask(task);
    } else if (agent.execute) {
      // 通用工具
      return {
        success: true,
        result: await agent.execute(task),
      };
    } else if (typeof agent === 'function') {
      // 函数式代理
      const result = await agent(task);
      return {
        success: true,
        result,
      };
    } else {
      throw new Error('Agent does not have a valid execution method');
    }
  }

  // 便捷方法：写作
  public async write(
    prompt: string,
    options: { style?: string; agent?: string; priority?: number } = {}
  ): Promise<string> {
    const agentName = options.agent || 'writing';
    const agent = this.getAgent(agentName);

    if (!agent) {
      throw new Error(`Agent not found: ${agentName}`);
    }

    const task = {
      id: uuidv4(),
      type: 'generate',
      input: prompt,
      options: { style: options.style },
      priority: 1,
      createdAt: new Date(),
    };

    const result = await this.executeTask(agentName, task, { priority: options.priority });

    if (!result.result.success) {
      throw new Error(result.result.error || 'Writing task failed');
    }

    return result.result.result || '';
  }

  // 便捷方法：润色
  public async polish(
    text: string,
    options: { style?: string; agent?: string; priority?: number } = {}
  ): Promise<string> {
    const agentName = options.agent || 'writing';
    const agent = this.getAgent(agentName);

    if (!agent || !agent.polish) {
      throw new Error(`Polish not supported by agent: ${agentName}`);
    }

    const task = {
      id: uuidv4(),
      type: 'polish',
      input: text,
      options: { style: options.style },
      priority: options.priority || 2, // 润色优先级较高
      createdAt: new Date(),
    };

    const result = await this.executeTask(agentName, task, { priority: options.priority });

    if (!result.result.success) {
      throw new Error(result.result.error || 'Polish task failed');
    }

    return result.result.result || '';
  }

  // 便捷方法：扩写
  public async expand(
    text: string,
    options: { direction?: string; agent?: string; priority?: number } = {}
  ): Promise<string> {
    const agentName = options.agent || 'writing';
    const agent = this.getAgent(agentName);

    if (!agent || !agent.expand) {
      throw new Error(`Expand not supported by agent: ${agentName}`);
    }

    const task = {
      id: uuidv4(),
      type: 'expand',
      input: text,
      options: { expansionDirection: options.direction },
      priority: options.priority || 1,
      createdAt: new Date(),
    };

    const result = await this.executeTask(agentName, task, { priority: options.priority });

    if (!result.result.success) {
      throw new Error(result.result.error || 'Expand task failed');
    }

    return result.result.result || '';
  }

  // 便捷方法：续写
  public async continue(
    text: string,
    options: { context?: string; agent?: string; priority?: number } = {}
  ): Promise<string> {
    const agentName = options.agent || 'writing';
    const agent = this.getAgent(agentName);

    if (!agent || !agent.continue) {
      throw new Error(`Continue not supported by agent: ${agentName}`);
    }

    const task = {
      id: uuidv4(),
      type: 'continue',
      input: text,
      options: { context: options.context },
      priority: options.priority || 2,
      createdAt: new Date(),
    };

    const result = await this.executeTask(agentName, task, { priority: options.priority });

    if (!result.result.success) {
      throw new Error(result.result.error || 'Continue task failed');
    }

    return result.result.result || '';
  }

  // 便捷方法：摘要
  public async summarize(
    text: string,
    options: { length?: number; agent?: string; priority?: number } = {}
  ): Promise<string> {
    const agentName = options.agent || 'writing';
    const agent = this.getAgent(agentName);

    if (!agent || !agent.summarize) {
      throw new Error(`Summarize not supported by agent: ${agentName}`);
    }

    const task = {
      id: uuidv4(),
      type: 'summarize',
      input: text,
      options: { targetLength: options.length },
      priority: options.priority || 1,
      createdAt: new Date(),
    };

    const result = await this.executeTask(agentName, task, { priority: options.priority });

    if (!result.result.success) {
      throw new Error(result.result.error || 'Summarize task failed');
    }

    return result.result.result || '';
  }

  // 获取执行器状态
  public getStatus(): {
    queueLength: number;
    runningTasks: number;
    totalAgents: number;
    executionHistory: number;
    isProcessing: boolean;
  } {
    return {
      queueLength: this.taskQueue.length,
      runningTasks: this.runningTasks.size,
      totalAgents: this.agents.size,
      executionHistory: this.executionHistory.length,
      isProcessing: this.isProcessing,
    };
  }

  // 获取执行历史
  public getExecutionHistory(limit?: number): ExecutionResult[] {
    if (limit) {
      return this.executionHistory.slice(-limit);
    }
    return [...this.executionHistory];
  }

  // 清空队列
  public clearQueue(): void {
    this.taskQueue = [];
  }

  // 清空历史
  public clearHistory(): void {
    this.executionHistory = [];
  }

  // 取消任务
  public cancelTask(taskId: string): boolean {
    // 从队列中移除
    const queueIndex = this.taskQueue.findIndex(t => t.id === taskId);
    if (queueIndex !== -1) {
      this.taskQueue.splice(queueIndex, 1);
      return true;
    }

    // 如果正在运行，无法取消（简化实现）
    if (this.runningTasks.has(taskId)) {
      console.warn(`Cannot cancel running task: ${taskId}`);
      return false;
    }

    return false;
  }

  // 更新配置
  public updateConfig(newConfig: Partial<AgentExecutorConfig>): void {
    this.config = { ...this.config, ...newConfig };
  }

  // 获取代理统计信息
  public getAgentStats(): Record<string, any> {
    const stats: Record<string, any> = {};

    this.agents.forEach((agent, name) => {
      if (agent.getStats) {
        stats[name] = agent.getStats();
      } else {
        stats[name] = { type: 'unknown' };
      }
    });

    return stats;
  }

  // 健康检查
  public async healthCheck(): Promise<Record<string, any>> {
    const health: Record<string, any> = {
      executor: this.getStatus(),
      agents: {},
    };

    // 检查每个代理
    for (const [name, agent] of this.agents) {
      try {
        if (agent.testConnection) {
          health.agents[name] = {
            status: 'healthy',
            response: await agent.testConnection(),
          };
        } else {
          health.agents[name] = { status: 'unknown' };
        }
      } catch (error) {
        health.agents[name] = {
          status: 'unhealthy',
          error: error instanceof Error ? error.message : 'Unknown error',
        };
      }
    }

    return health;
  }
}

// 导出便捷函数
export const createAgentExecutor = (config?: Partial<AgentExecutorConfig>): AgentExecutor => {
  return new AgentExecutor(config);
};

// 默认实例
export const defaultAgentExecutor = new AgentExecutor();